package com.fdb.efp.nls.service.impl.psd.credit;

import com.fdb.efp.edoc.service.facade.signature.PsdContResult;
import com.fdb.efp.nls.service.domain.signature.SignatureRecord;
import com.fdb.efp.nls.service.domain.sx.NlsCreditInfo;
import com.fdb.efp.nls.service.facade.psd.PsdSqsSignatureService;
import com.fdb.efp.nls.service.vo.signature.SignatureRecordVO;
import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.efp.nls.common.psd.PsdConstantSet;
import com.fdb.efp.nls.service.facade.SCfgParamService;
import com.fdb.efp.console.service.vo.SCfgParamVO;
import com.fdb.efp.cus.service.facade.CusIndivService;
import com.fdb.efp.nls.service.vo.CfcaSignInfoVO;
import com.fdb.efp.nls.service.vo.ImageBizDetailVO;
import com.fdb.efp.nls.service.vo.ImageBizInfoVO;
import com.fdb.efp.nls.service.facade.CfcaSignInfoService;
import com.fdb.efp.nls.service.facade.ImageBizDetailService;
import com.fdb.efp.nls.service.facade.ImageBizInfoService;
import com.fdb.efp.nls.service.facade.signature.PsdCertUploadService;
import com.fdb.efp.nls.service.facade.signature.PsdContService;
import com.fdb.efp.esb.common.constant.ElectronicSignatureEnums;
import com.fdb.efp.nls.service.dao.signature.SignatureRecordDAO;
import com.fdb.efp.nls.service.dao.sx.NlsCreditInfoDao;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 普税贷授权书签章服务类--
 *
 * @author xiaojunhui<br />
 */
@Service("psdSqsSignatureService")
public class PsdSqsSignatureServiceImpl implements PsdSqsSignatureService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(PsdSqsSignatureServiceImpl.class);

    @Autowired
    private SignatureRecordDAO signatureRecordDAO;

    @Autowired
    private NlsCreditInfoDao nlsCreditInfoDao;

    @Autowired
    @Qualifier("cfcaSignInfoService")
    private CfcaSignInfoService cfcaSignInfoService;

    @Autowired
    private SCfgParamService sCfgParamService;

    @Autowired
    private PsdContService psdContService;

    @Autowired
    private PsdCertUploadService psdCertUploadService;


    @Autowired
    private CusIndivService cusIndivService;


    @Override
    public Boolean signature() {
        logger.info("开始进行在线签章");
        //获取配置的处理数量以及重试次数
        final int[] handleNumArr = getHandleNumArr();
        //获取待签订的数据
        final List<SignatureRecord> SignatureRecords = signatureRecordDAO.getSignatureNlsList(PsdConstantSet.prdId, handleNumArr[1], PsdConstantSet.PSD_FILE_TYPE_03, handleNumArr[0]);

        if (SignatureRecords == null || SignatureRecords.isEmpty()) {
            logger.info("在线签章：获取到需要处理的数据为空");
            return Boolean.TRUE;
        }
        for (SignatureRecord signatureRecord : SignatureRecords) {
            try {
                signatureRecord.setRetryNum(signatureRecord.getRetryNum() + 1);
                //判断状态 如果是02 那么需要走流程 如果是3 直接走下载
                if (signatureRecord.getSiuSta() == 1) {
                    continue;
                }
                String applySeq = signatureRecord.getApplySeq();
                NlsCreditInfo pkParam = new NlsCreditInfo();
                pkParam.setLmtApplySeq(applySeq);
                final NlsCreditInfo nlsCreditInfo = nlsCreditInfoDao.queryByPk(pkParam);
                if (Objects.isNull(nlsCreditInfo)) {
                    if (signatureRecord.getSiuSta() == 0) {
                        signatureRecord.setSiuSta(2);
                    }
                    signatureRecord.setLastUpdateTime(new Date());
                    signatureRecord.setErrMsg("查询授信信息为空");
                    signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                    continue;
                }
                //判断状态 如果是2 那么需要走签章流程流程 如果是3 直接走下载
                if (signatureRecord.getSiuSta() == 3) {

                    final PsdContResult psdContResult = psdContService.downSignFile(nlsCreditInfo.getLmtApplySeq(), signatureRecord.getSiuContNo(), nlsCreditInfo.getLmtApplySeq() + "_sqs.pdf");
                    if (psdContResult.isRetFlag()) {
                        signatureRecord.setSiuSta(1);
                        signatureRecord.setLastUpdateTime(new Date());
                        //signatureRecord.setSiuContNo(psdContResult.getAxqContNo());
                        signatureRecord.setDwnRetMsg("下载文件成功");
                        signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                        psdCertUploadService.insert(psdContResult.getFileFullPath());
                        insertCfcaSignInfo(psdContResult,nlsCreditInfo,signatureRecord.getSiuContNo());
                        //插入明细表
                        insertImageBizDetail(nlsCreditInfo, PsdConstantSet.PSD_FILE_TYPE_03, FilenameUtils.getBaseName(psdContResult.getFileFullPath()),psdContResult.getFileFullPath());
                        insertImageBizInfo(nlsCreditInfo);
                        continue;
                    } else {
                        signatureRecord.setSiuSta(3);
                        signatureRecord.setLastUpdateTime(new Date());
                        signatureRecord.setDwnRetMsg(psdContResult.getMsg());
                        signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                        continue;
                    }
                }
                if (signatureRecord.getSiuSta() == 0 || signatureRecord.getSiuSta() == 2) {
                    //为空就开户
                    HashMap<String, String> paramMap = new HashMap<>();
                    paramMap.put("cusName", nlsCreditInfo.getCusName());
                    paramMap.put("certNo", nlsCreditInfo.getCertCode());
                    paramMap.put("signDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
                    final PsdContResult signatureResult = psdContService.signature(nlsCreditInfo.getLmtApplySeq(), getAxqUserId(nlsCreditInfo), "sqs.pdf", "个人授权书", paramMap);
                    if (signatureResult.isRetFlag()) {
                        signatureRecord.setSiuContNo(signatureResult.getAxqContNo());
                        signatureRecord.setSiuRetMsg("签署授权书成功");
                        //成功走下载流程
                        final PsdContResult psdContResult = psdContService.downSignFile(nlsCreditInfo.getLmtApplySeq(), signatureRecord.getSiuContNo(), nlsCreditInfo.getLmtApplySeq() + "_sqs.pdf");
                        if (psdContResult.isRetFlag()) {
                            signatureRecord.setSiuSta(1);
                            signatureRecord.setLastUpdateTime(new Date());
                            //signatureRecord.setSiuContNo(psdContResult.getAxqContNo());
                            signatureRecord.setDwnRetMsg("下载文件成功");
                            signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                            insertCfcaSignInfo(psdContResult, nlsCreditInfo,signatureRecord.getSiuContNo());
                            psdCertUploadService.insert(psdContResult.getFileFullPath());
                            //插入明细表
                            insertImageBizDetail(nlsCreditInfo, PsdConstantSet.PSD_FILE_TYPE_03, FilenameUtils.getBaseName(psdContResult.getFileFullPath()),psdContResult.getFileFullPath());
                            insertImageBizInfo(nlsCreditInfo);
                            continue;
                        } else {
                            signatureRecord.setSiuSta(3);
                            signatureRecord.setLastUpdateTime(new Date());
                            signatureRecord.setDwnRetMsg(psdContResult.getMsg());
                            signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                            continue;
                        }

                    } else {
                        signatureRecord.setSiuSta(2);
                        signatureRecord.setSiuRetMsg(signatureResult.getMsg());
                        signatureRecord.setLastUpdateTime(new Date());
                        signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                        continue;
                    }
                }

            } catch (Exception e) {
                logger.error("处理签章发生异常", e);
                signatureRecord.setErrMsg(e.getMessage());
                signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                continue;
            }

        }
        return Boolean.TRUE;
    }

    private String getAxqUserId( NlsCreditInfo nlsCreditInfo) throws Exception {
        PsdContResult openAccountResult = psdContService.openAccount(nlsCreditInfo.getCusName(), nlsCreditInfo.getCertType(), nlsCreditInfo.getCertCode(), nlsCreditInfo.getEmail(), nlsCreditInfo.getIndivMobile(), nlsCreditInfo.getIndivRsdAddr(), nlsCreditInfo.getLmtApplySeq());
        if (openAccountResult.isRetFlag()) {
            return openAccountResult.getAxqUserId();
        } else {
            throw new Exception(openAccountResult.getMsg());
        }
    }

    @Override
    public Integer insertRecord(SignatureRecordVO signatureRecordVO) {
        //如果存在记录则不再插入
        SignatureRecord signatureRecord = signatureRecordDAO.selectByPst(signatureRecordVO.getPrdId(), signatureRecordVO.getApplySeq(), signatureRecordVO.getLinkType());
        if (!Objects.isNull(signatureRecord)) {
            return 0;
        }
        return signatureRecordDAO.insert(beanCopy(signatureRecordVO, new SignatureRecord()));
    }

    @Override
    public Integer updateOperInfo(String lmtAppSeq, String userId, String orgId) {
        //需要改授权书、脱敏授权书、脱敏授信合同的所属结构和所属工号
        int updateSqsCount = 0;
        int updateSqsTmCount = 0;
        int updateSxcontTmCount = 0;
        CfcaSignInfoVO pkParam = new CfcaSignInfoVO();
        pkParam.setApplySeq(lmtAppSeq+"_sqs");
        CfcaSignInfoVO cfcaSignInfoVO = cfcaSignInfoService.queryByPk(pkParam);
        if (!Objects.isNull(cfcaSignInfoVO)) {
            cfcaSignInfoVO.setNlsOperOrgid(orgId);
            cfcaSignInfoVO.setNlsOperUserid(userId);
            cfcaSignInfoVO.setFinaBrId(orgId);
            updateSqsCount = cfcaSignInfoService.updateByPk(cfcaSignInfoVO);
        }
        pkParam.setApplySeq(lmtAppSeq + "_tm_sqs");
        cfcaSignInfoVO = cfcaSignInfoService.queryByPk(pkParam);
        if (!Objects.isNull(cfcaSignInfoVO)) {
            cfcaSignInfoVO.setNlsOperOrgid(orgId);
            cfcaSignInfoVO.setNlsOperUserid(userId);
            cfcaSignInfoVO.setFinaBrId(orgId);
            updateSqsTmCount = cfcaSignInfoService.updateByPk(cfcaSignInfoVO);
        }
        pkParam.setApplySeq(lmtAppSeq + "_tm_sxcont");
        cfcaSignInfoVO = cfcaSignInfoService.queryByPk(pkParam);
        if (!Objects.isNull(cfcaSignInfoVO)) {
            cfcaSignInfoVO.setNlsOperOrgid(orgId);
            cfcaSignInfoVO.setNlsOperUserid(userId);
            cfcaSignInfoVO.setFinaBrId(orgId);
            updateSxcontTmCount = cfcaSignInfoService.updateByPk(cfcaSignInfoVO);
        }
        return updateSqsCount + updateSqsTmCount + updateSxcontTmCount;
    }

    private void insertCfcaSignInfo(PsdContResult psdContResult,NlsCreditInfo nlsCreditInfo,String cfcaContNo) {
        CfcaSignInfoVO cfcaSignInfoVO = new CfcaSignInfoVO();
        //申请流水号
        cfcaSignInfoVO.setApplySeq(nlsCreditInfo.getLmtApplySeq() + "_sqs");
        //产品id
        cfcaSignInfoVO.setPrdId(nlsCreditInfo.getPrdId());
        //产品代码
        cfcaSignInfoVO.setPrdCode(nlsCreditInfo.getPrdCode());
        //产品名称
        cfcaSignInfoVO.setPrdName(nlsCreditInfo.getPrdName());
        //合同号
        //cfcaSignInfoVO.setContNo();
        //安心签合同号
        cfcaSignInfoVO.setCfcaContNo(cfcaContNo);
        //客户号
        cfcaSignInfoVO.setCusId(nlsCreditInfo.getCusId());
        //客户名称
        cfcaSignInfoVO.setCusName(nlsCreditInfo.getCusName());

        cfcaSignInfoVO.setFinaBrId(nlsCreditInfo.getNlsOperOrgid());
        cfcaSignInfoVO.setNlsOperOrgid(nlsCreditInfo.getNlsOperOrgid());
        cfcaSignInfoVO.setNlsOperUserid(nlsCreditInfo.getNlsOperUserid());
        //cfca签署状态 = “未签署”
        cfcaSignInfoVO.setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
        cfcaSignInfoVO.setCfcaSignTime(psdContResult.getAxqSignTime());
        cfcaSignInfoService.insertCfcaSignInfo(cfcaSignInfoVO);
    }


    private int[] getHandleNumArr() {
        int[] result = new int[2];
        try {
            SCfgParamVO param = new SCfgParamVO();
            param.setParamKey(PsdConstantSet.MAX_NUM_KEY);
            SCfgParamVO maxNumCfg = sCfgParamService.queryByPk(param);
            if (Objects.isNull(maxNumCfg)) {
                //设置默认值
                result[0] = 50;
            } else {
                result[0] = Integer.parseInt(maxNumCfg.getParamValue());
            }
            param.setParamKey(PsdConstantSet.RETRY_NUM_KEY);
            SCfgParamVO retryNumCfg = sCfgParamService.queryByPk(param);
            if (Objects.isNull(retryNumCfg)) {
                //设置默认值
                result[1] = 3;
            } else {
                result[1] = Integer.parseInt(retryNumCfg.getParamValue());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Autowired
    private ImageBizDetailService imageBizDetailService;

    /**
     * 插入记录到影响明细表
     * @param nlsCreditInfoVO
     * @param imgType
     * @param fileName
     * @param filePath
     */
    private void insertImageBizDetail(NlsCreditInfo nlsCreditInfoVO,String imgType,String fileName,String filePath) {
        ImageBizDetailVO imageBizDetail = new ImageBizDetailVO();
        imageBizDetail.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        imageBizDetail.setBizStage("授信阶段");
        imageBizDetail.setFileDesc("普税贷个人授权书");
        imageBizDetail.setFileName(fileName);
        imageBizDetail.setFilePath(filePath);
        imageBizDetail.setImageId(imgType);
        imageBizDetail.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizDetail.setImageType(imgType);
        imageBizDetailService.insertImageBizDetail(imageBizDetail);
    }

    @Autowired
    private ImageBizInfoService imageBizInfoService;
    /**
     * 插入数据到影像业务信息
     *
     * @param nlsCreditInfoVO 目标文件
     */
    private void insertImageBizInfo(NlsCreditInfo nlsCreditInfoVO) {
        ImageBizInfoVO param = new ImageBizInfoVO();
        param.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        if (!Objects.isNull(imageBizInfoService.queryByPk(param))) {
            return;
        }
        ImageBizInfoVO imageBizInfo = new ImageBizInfoVO();
        imageBizInfo.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        imageBizInfo.setCreateDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        imageBizInfo.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizInfo.setCusId(nlsCreditInfoVO.getCusId());
        imageBizInfo.setCusName(nlsCreditInfoVO.getCusName());
        imageBizInfo.setPrdId(nlsCreditInfoVO.getPrdId());
        imageBizInfo.setPrdCode(nlsCreditInfoVO.getPrdCode());
        imageBizInfo.setPrdName(nlsCreditInfoVO.getPrdName());
        //如下信息先赋空值
        imageBizInfo.setSoltImageAccept("");
        imageBizInfo.setSoltImageCfca("");
        imageBizInfo.setSoltImageThird1("");
        imageBizInfo.setSoltImageThird2("");
        imageBizInfoService.insertOrUpdateImageBizInfoVO(imageBizInfo);
    }

}